##parameters=assessmentIdentity, actionIdentity, assignTo=None, comments=None, came_from=None

form = context.REQUEST.form

from DateTime import DateTime

now = DateTime().strftime("%d %b %Y %H:%M")


username = str( context.REQUEST.AUTHENTICATED_USER )
    
userProviderService = context.knowledgeengine_userproviderservice
user = userProviderService.getUser( username )
             
action = context.getComponentByIdentity( actionIdentity )

ass = context.knowledgeengine_assessmentstorageservice 
assessment = ass.loadAssessment( assessmentIdentity, userIdentity=user.getIdentity())
    
# Process embedded components 
changelog = context.embedComponent_process( assessmentIdentity, form )    

logged = False
if changelog:
    ass.logWorkflowChange( assessment, action, comments, changelog )
    logged = True
        
# Changing workflow states may remove the assessment from the users personal repository.
# Remember the current user so we can re-add later if needed.
#oldAuthor = context.getIPOwner( assessmentIdentity )

#oldState     = context.getIPWorkflowState( assessmentIdentity )

#newState = None
msg = ""
if assignTo:    
    assessment.setResponsible( assignTo )
    ass.saveAssessment( assessment )    
    
    assignToUser = context.portal_membership.getMemberById( assignTo )
    if assignToUser:
        msg += "Assigning to user '%s'\n" % ( assignToUser.getProperty('fullname') or assignToUser.getId() )
    else:
        msg += "Assigning to user '%s'\n" % assignTo

# First, trigger the action
if actionIdentity:
    
    if not action:
        raise "Unable to find action %s" % actionIdentity

    if logged:
        action.execute( assessment, user, workflowComments=' ' )
    else:
        action.execute( assessment, user, workflowComments=comments )
    
    ass.saveAssessment(assessment)
    
    #newState = context.getIPWorkflowState( assessmentIdentity )
    
    msg += "Executing action %s\n" % `action.title_or_id()`
    
    # This is now triggered directly by the assessment action, no need to log here.
    #ass.logWorkflowChange( assessment, action, comments, msg )    
    logged = True
    
else:
    action = None
    if not msg: msg    = "(No Action)"
    

# If no previous action has triggered a workflog log hit, do so now
if not logged:
    ass.logWorkflowChange( assessment, None, comments, msg )        



    
redirect = context.REQUEST.RESPONSE.redirect
msg = "Workflow status updated"

if not came_from:
    came_from = "workflow_form?assessmentIdentity=%s" % assessmentIdentity
if not '?' in came_from:
    came_from += "?"


url = '%s&portal_status_message=%s' % (came_from, msg)

return redirect(url)
